package com.achun.getcouponleague.presenter.impl;

import com.achun.getcouponleague.Bean.Category;
import com.achun.getcouponleague.model.ServiceApi;
import com.achun.getcouponleague.presenter.IHomePresenter;
import com.achun.getcouponleague.utils.Logutils;
import com.achun.getcouponleague.utils.RetrogitManager;
import com.achun.getcouponleague.view.IHomeCallback;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomePresenter implements IHomePresenter {
    private IHomeCallback iHomeCallback;

    @Override
    public void getCategories() {
        if (iHomeCallback != null) {

            iHomeCallback.onLoading();
        }
        //加载分类数据
        Retrofit retrofit = RetrogitManager.getInstance().getRetrofit();
        ServiceApi serviceApi = retrofit.create(ServiceApi.class);
        Call<Category> task = serviceApi.getCategories();
        task.enqueue(new Callback<Category>() {
            @Override
            public void onResponse(Call<Category> call, Response<Category> response) {

                    //请求成功
                    Category category = response.body();
                    if (iHomeCallback!=null) {
                        if (category == null || category.getData().size() == 0) {
                            iHomeCallback.onEmpty();
                        } else {
                            iHomeCallback.onCategoriesLoaded(category);
                            Logutils.e(this.getClass(),category.getData().toString());
                        }
                    }


            }

            @Override
            public void onFailure(Call<Category> call, Throwable t) {
                Logutils.e(this.getClass(),"请求错误---》"+t.toString());
                if (iHomeCallback != null) {
                    iHomeCallback.onError();
                }
//错误回调
            }
        });

    }

    @Override
    public void registerCallback(IHomeCallback iHomeCallback) {
        this.iHomeCallback=iHomeCallback;
    }

    @Override
    public void unRegisterCallback(IHomeCallback iHomeCallback) {

    }
}
